package dao.xml.sax;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import model.Datentraeger;
import model.Film;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxExample extends DefaultHandler 
{

  private final SAXParser parser;
  private List<Datentraeger> datentraeger;
  private Datentraeger currentDatentraeger;

  public SaxExample() throws ParserConfigurationException, SAXException 
  {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    factory.setXIncludeAware(false);
    parser = factory.newSAXParser();
  }

  public List<Datentraeger> getDatentraegers(InputStream input) throws SAXException, IOException 
  {
    parser.parse(input, this);
    return datentraeger;
  }

  @Override
  public void startDocument() throws SAXException 
  {
	  datentraeger = new ArrayList<Datentraeger>();
  }

  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
  {
    if ("datentraeger".equals(qName)) 
    {
      currentDatentraeger = new Datentraeger(attributes.getValue("name"));
      datentraeger.add(currentDatentraeger);
    }
    else if ("film".equals(qName)) 
    {
      String name = attributes.getValue("name");
      String hauptdarsteller = attributes.getValue("hauptdarsteller");
      String genre = attributes.getValue("genre");
//      Film film = new Film(name, hauptdarsteller, genre);
      Film film = new Film((long) 1234, name, hauptdarsteller, genre, Integer.valueOf(attributes.getValue("laenge")));
//      film.setLaenge(Integer.valueOf(attributes.getValue("laenge")));
      currentDatentraeger.addFilm(film);
    }
  }

}
